package cn.hust.springboot.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Controller
public class ErrorHandlerController implements ErrorController {
    @Autowired
    private ErrorAttributes errorAttributes;
    @RequestMapping("/error")
    public String handleError(HttpServletRequest request, Model model){
        //错误详情
        ServletWebRequest servletWebRequest = new ServletWebRequest(request);
        Map<String, Object> errorAttributes = this.errorAttributes.getErrorAttributes(servletWebRequest, true);
        //根据状态码返回到对应页面
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if(statusCode == 400){
            model.addAttribute("code", "400");
            model.addAttribute("msg", "请检查输入的数据是否有错，如仍存在问题，请联系管理员");
            return "/400";
        }else if(statusCode == 403){
            model.addAttribute("code", "403");
            model.addAttribute("msg", "资源不可用");
            return "/403";
        }else if(statusCode == 404){
            model.addAttribute("code", "404");
            model.addAttribute("msg", "请检查输入的网址是否有错，如仍存在问题，请联系管理员");
            return "/404";
        }else{
            model.addAttribute("code", "500");
            model.addAttribute("msg", "服务器内部错误");
            return "/500";
        }
    }
    @Override
    public String getErrorPath() {
        return "/error";  //出错之后，找哪个mapping处理，就是上面这个handleError()方法
    }
}
